﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using DataPump;

namespace DataPump
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DateTime start = GetLastDoTime();
                Console.WriteLine("任务开始执行，将采集时间大于：" + start.ToString() + "的数据");
                string constr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectStr"].ConnectionString;
                IResource resource = new ganjiResource(constr, start);
                resource.Do();
                resource.DoAutoRefresh();
                Console.WriteLine(String.Format("共分析：{0}条数据{1}{2}条数据被记录{3}{4}因为数据异常被跳过{5}{6}因为非记录时间被跳过{7}{8}因为联系方式为空被跳过{9}{10}因为包含敏感文字被跳过{11}{12}因为重复被跳过",
                    resource.total,
                    Environment.NewLine, resource.recrod,
                    Environment.NewLine, resource.jumpwitherror,
                    Environment.NewLine, resource.jumpwithtime,
                    Environment.NewLine, resource.jumpwithempty,
                    Environment.NewLine, resource.jumpwithganji,
                    Environment.NewLine, resource.repeat));
                Console.WriteLine("本次任务完成。记录结束时间为：" + OverWriteDoTime() + "，按任意键退出");
                Console.WriteLine("开始创建索引");
                new com.yaojianzhi.ExchangeServiceSoapClient().DoPositionIndex("exchangeservice@chongshantech");
                Console.WriteLine("重建索引完成");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadKey();
        }
        static DateTime OverWriteDoTime() 
        {
            DateTime dt = DateTime.Now;
            using (System.IO.StreamWriter sw = new StreamWriter("perpare.data",false))
            {
                sw.Write(dt.ToString());
            }
            return dt;
        }
        static DateTime GetLastDoTime()
        {
            if (!System.IO.File.Exists("perpare.data"))
            {
                return DateTime.Now;
            }
            using (System.IO.StreamReader sr = new StreamReader("perpare.data"))
            {
                try
                {
                    string str = sr.ReadLine();
                    DateTime dt = DateTime.Now;
                    if (DateTime.TryParse(str, out dt))
                    {
                        return dt;
                    }
                }
                catch { }
                return DateTime.Now;
            }
        }
    }


    #region Common
    public static class Common
    {
        static int idx = 1;           //"51944179@qq.com", "214936150@qq.com", "1654625358@qq.com", "634691728@qq.com"
        static string[] recruiter = { "1768050400@qq.com", "1617047154@qq.com", "1274584051@qq.com" };
        public static string DoRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Accept = "*/*";
            request.KeepAlive = true;
            request.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");

            HttpWebResponse response = null;
            response = (HttpWebResponse)request.GetResponse();

            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            using (StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("utf-8")))
            {
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                responseFromServer = responseFromServer.Replace("\r", "").Replace("\n", "");
                return responseFromServer;
            }
        }
        public static DateTime ToDate(this string date)
        {
            DateTime dt = DateTime.Now;
            if (DateTime.TryParse(date, out dt))
            {
                return dt;
            }
            return DateTime.Now;
        }
        public static void RecordToDB(ref int count, List<Info> data)
        {
            using (SqlConnection con = new SqlConnection("Data Source=Sql1001.webweb.com,2433;Initial Catalog=DB_98EBF3_ueEngine;User ID=DB_98EBF3_ueEngine_admin;Password=ueEngine2012;Asynchronous Processing=true"))
            {
                con.Open();
                foreach (var item in data)
                {
                    try
                    {
                        SqlCommand com = con.CreateCommand();
                        com.CommandText = String.Format("insert into SourceData values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}'," +
                        "'{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}')",
                        item.orgId, item.Caption, item.PublishDate.ToShortDateString(), item.ContactMan, item.ContactPhone, item.Area, item.Address,
                        item.PositionType, item.PositionName, item.Vacancy, item.Salry, item.Period, item.Experience, item.Degree, item.PositionDescript,
                        item.CompanyName, item.CopBusiness, item.CopType, item.CopAbout, item.CopDimensions);
                        com.CommandType = System.Data.CommandType.Text;
                        int affect = com.ExecuteNonQuery();
                        if (affect == 1)
                        {
                            Console.WriteLine("还剩" + --count + "条数据等待写入");
                        }
                        com.Dispose();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("写入第：" + --count + "数据时出现异常" + Environment.NewLine + e.Message);

                        using (System.IO.StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "writeToDbErr.txt"))
                        {
                            sw.WriteLine(e.ToString());
                        }
                    }
                }
            }
        }
        public static string GetRecruiter()
        {
            idx = idx == recruiter.Length ? 0 : idx + 1;
            return recruiter[idx % recruiter.Length];
        }
    }
    #endregion

    #region Data
    public class Info
    {
        public string orgId { get; set; }

        public string Caption { get; set; }
        public DateTime PublishDate { get; set; }
        public string ContactMan { get; set; }
        public string ContactPhone { get; set; }
        public int Area { get; set; }
        public string Address { get; set; }

        //职位
        public int PositionType { get; set; }
        public string PositionName { get; set; }
        public string Vacancy { get; set; }
        public string Salry { get; set; }
        public string Period { get; set; }
        public string Experience { get; set; }
        public string Degree { get; set; }
        public string PositionDescript { get; set; }

        //company
        public string CompanyName { get; set; }
        /// <summary>
        /// 公司行业
        /// </summary>
        public string CopBusiness { get; set; }
        /// <summary>
        /// 公司性质
        /// </summary>
        public string CopType { get; set; }
        /// <summary>
        /// 规模
        /// </summary>
        public string CopDimensions { get; set; }
        /// <summary>
        /// 公司简介
        /// </summary>
        public string CopAbout { get; set; }
    }
    public class PerpareData
    {
        public DateTime LastTime { get; set; }
    }
    #endregion
}
